package cn.aopmin;

import cn.aopmin.listener.DemoEvent;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

@EnableAsync
@SpringBootApplication
public class Launcher {
    public static void main(String[] args) {
        ConfigurableApplicationContext app = SpringApplication.run(Launcher.class, args);
        for (int i = 0; i < 5; i++) {
            app.publishEvent(new DemoEvent("", "hello" + i, 1));
        }
    }

    /**
     * 创建自定义线程池
     * @return ThreadPoolTaskExecutor 线程池实例
     */
    @Bean(name = "customThreadPool")
    public ThreadPoolTaskExecutor customThreadPool() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();

        // 核心线程数：线程池中始终保留的线程数量
        executor.setCorePoolSize(5);
        // 最大线程数：线程池允许的最大线程数
        executor.setMaxPoolSize(10);
        // 队列容量：线程池所使用的任务队列大小
        executor.setQueueCapacity(20);
        // 线程存活时间：非核心线程闲置超过此时间后会被回收
        executor.setKeepAliveSeconds(30);
   /*      // 线程名前缀：用于区分线程池中的线程
        executor.setThreadNamePrefix("custom-thread-"); */
        // 拒绝策略：当线程池无法接受新任务时的应对策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 初始化线程池
        executor.initialize();
        return executor;
    }
}
